import time
import comtypes as com
import comtypes.client as coclient
import comtypes.persist as persist
dshow = coclient.GetModule('dshow.tlb')

CLSID_VideoInputDeviceCategory = com.GUID('{860BB310-5D01-11d0-BD3B-00A0C911CE86}')
CLSID_AudioInputDeviceCategory = com.GUID('{33D9A762-90C8-11d0-BD43-00A0C911CE86}')
PIN_CATEGORY_PREVIEW = com.GUID('{fb6c4282-0353-11d1-905f-0000c0cc16ba}')
PIN_CATEGORY_CAPTURE = com.GUID('{fb6c4281-0353-11d1-905f-0000c0cc16ba}')
MEDIATYPE_Video = com.GUID('{73646976-0000-0010-8000-00AA00389B71}')
MEDIATYPE_Audio = com.GUID('{73647561-0000-0010-8000-00AA00389B71}')

def bindwrap(fn):
    def newfn(self, riid, pbc=None, pmk=None):
        return fn(self, pbc, pmk, riid._iid_).QueryInterface(riid)
    setattr(fn.im_class, fn.__name__, newfn)
bindwrap(dshow.IMoniker.BindToStorage)
bindwrap(dshow.IMoniker.BindToObject)

def preview():
    ifgm = coclient.CreateObject(dshow.FilterGraph, com.CLSCTX_INPROC_SERVER)
    icgb = coclient.CreateObject(dshow.CaptureGraphBuilder2, com.CLSCTX_INPROC_SERVER)
    isde = coclient.CreateObject(dshow.SystemDeviceEnum, com.CLSCTX_INPROC_SERVER)
    icgb.SetFiltergraph(ifgm)
    for imk in isde.CreateClassEnumerator(CLSID_VideoInputDeviceCategory, 0):
        ipb = imk.BindToStorage(persist.IPropertyBag)
        print repr(ipb.Read("FriendlyName", "<unknown>", None)) #, repr(ipb.Read("DevicePath", "", None))
    ividcap = imk.BindToObject(dshow.IBaseFilter)
    ifgm.AddFilter(ividcap, "Video Capture Filter")
    for imk in isde.CreateClassEnumerator(CLSID_AudioInputDeviceCategory, 0):
#        ipb = imk.BindToStorage(None, None, persist.IPropertyBag._iid_).QueryInterface(persist.IPropertyBag)
        ipb = imk.BindToStorage(persist.IPropertyBag)
        print ipb.Read("FriendlyName", "<unknown>", None) #, repr(ipb.Read("DevicePath", "", None))
#    iaudcap = imk.BindToObject(dshow.IBaseFilter)
#    ifgm.AddFilter(iaudcap, "Audio Capture Filter")

    icgb.RenderStream(PIN_CATEGORY_PREVIEW, MEDIATYPE_Video, ividcap, None, None)
#    icgb.ControlStream(PIN_CATEGORY_PREVIEW, MEDIATYPE_Video, ividcap, 0, 0, 1, 2)
    imc = ifgm.QueryInterface(dshow.IMediaControl)
    ievt = ifgm.QueryInterface(dshow.IMediaEventEx)
#    coclient.ShowEvents(ifgm)
    coclient.PumpEvents(3)
    imc.Run()
    coclient.PumpEvents(4)
    print ievt.WaitForCompletion(3000)
#    while True:
 #       a,b,c = ievt.GetEvent(500)
  #      print a,b,c
  #      ievt.FreeEventParams(a,b,c)
#    time.sleep(10)
##    raw_input()

